// "e8:4a:54:60:f8:65"

#include <Arduino.h>
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>

#define SCAN_TIME 5                     // 扫描时间（秒）
#define MI_BLE_MAC "e8:4a:54:60:f8:65"  // MAC
#define C_PIN 8                         // IO8 按钮控制
#define R_PIN 9                         // IO9 按键状态读取,0打开
#define LED_PIN 12                      // IO12

BLEScan* pBLEScan;
bool isConnected = false;
int isOpen = 0;

void setup() {
  Serial.begin(115200);
  Serial.println("ESP32 BLE Client");

  pinMode(C_PIN, OUTPUT);
  digitalWrite(C_PIN, HIGH);
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);

  pinMode(R_PIN, INPUT_PULLUP);

  BLEDevice::init("");              // 初始化BLE设备
  pBLEScan = BLEDevice::getScan();  // 创建BLE扫描对象
  pBLEScan->setActiveScan(true);    // 启用主动扫描
  pBLEScan->setInterval(100);       // 扫描间隔时间
  pBLEScan->setWindow(99);          // 扫描窗口
}

BLEAdvertisedDevice* miDevice = nullptr;

class MiClientCallback : public BLEClientCallbacks {
  void onConnect(BLEClient* pClient) {
    Serial.println("成功连接到设备！");
    isConnected = true;
    if (digitalRead(R_PIN) == HIGH) {
      // 按键模拟，关闭状态才执行
      btnAct();
    }
  }

  void onDisconnect(BLEClient* pClient) {
    Serial.println("设备已断开连接！");
    isConnected = false;
    if (digitalRead(R_PIN) == LOW) {
      // 按键模拟，开启状态才执行
      btnAct();
    }
  }
};

void connectToDevice() {
  if (miDevice != nullptr) {
    Serial.println("正在连接到设备...");
    BLEClient* pClient = BLEDevice::createClient();
    pClient->setClientCallbacks(new MiClientCallback());  // 设置回调函数
    pClient->connect(miDevice);                           // 连接到设备
    Serial.println("连接成功！");
  }
}

void btnAct() {
  digitalWrite(C_PIN, LOW);  // 模拟按下
  delay(500);
  digitalWrite(C_PIN, HIGH);  // 模拟松开
  delay(50);
}

void loop() {
  if (!isConnected) {
    Serial.println("开始扫描...");
    BLEScanResults foundDevices = pBLEScan->start(SCAN_TIME, false);  // 执行扫描

    for (int i = 0; i < foundDevices.getCount(); i++) {
      BLEAdvertisedDevice device = foundDevices.getDevice(i);
      if (device.getAddress().toString() == MI_BLE_MAC) {
        miDevice = &device;
        if (digitalRead(R_PIN) == HIGH) {
          btnAct();
        }
        connectToDevice();
        break;
      }
    }
  } else {
    Serial.println("与设备保持连接...");
  }

  delay(2000);  // 每隔2秒扫描一次
}
